package com.happy3w.ssp.schoolmatehome.service.auth;

import com.happy3w.ssp.schoolmatehome.interceptor.AttributeKeys;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtRequestFilter extends OncePerRequestFilter {
    private final UserCache userCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        JwtToken jwtToken = JwtToken.extract(request.getHeader("Authorization"));

        TheUserDetail userDetail;
        if (jwtToken != null) {
            Long userId = Long.parseLong(jwtToken.getSubject());
            userDetail = userCache.getUserDetail(userId);
        } else {
            userDetail = TheUserDetail.anonymous;
        }
        request.setAttribute(AttributeKeys.USER_DETAIL, userDetail);

        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                userDetail, null, userDetail.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authToken);
        filterChain.doFilter(request, response);

        if (jwtToken == null && response.getStatus() == HttpStatus.FORBIDDEN.value()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    }
}
